export const useCacheStore = defineStore('cache', () => {
  let menuList = $ref([]) // 菜单列表
  let roleList = $ref([]) // 角色列表
  let deptList = $ref([]) // 部门列表

  const roleListOptions = computed(() => {
    return roleList.map(e => {
      return { value: e.role_code, label: e.role_name }
    })
  })

  const updateMenus = (payload) => {
    menuList = payload
  }
  // 根据表名获取列表数据
  const getTableList = async ({ tableName, id, dataList = [] }) => {
    if (isNilOrEmpty(tableName)) return []
    const { status, data } = await Fetch(`/api/s/t/${tableName}`, {
      method: 'post',
      headers: { timestamp: Date.now() },
      data: objectNilClean({ limit: 1000, id }),
    })
    if (status !== 200 || data.code !== 0) {
      message.error(data?.msg || `获取表${tableName}数据失败！`)
      return []
    }
    if (id && isNotNilOrEmpty(dataList)) {
      data.result.dataList.forEach(e => {
        const idx = dataList.findIndex(v => v.id === e.id)
        if (idx < 0) {
          dataList.push(e)
          return
        }
        dataList.splice(idx, 1, e)
      })
    } else {
      dataList = data.result.dataList
    }
    return dataList
  }
  // 根据 id 更新列表数据
  const updateListById = async ({ tableName, dataList, id }) => {
    const idList = isArray(id) ? id : id.split(',')
    const datas = dataList.filter(e => idList.includes(e.id))
    if (idList.length === datas.length) {
      return idList.length === 1 ? datas[0] : datas
    }
    const dataIds = datas.map(e => e.id)
    const getIds = idList.filter(e => !dataIds.includes(e.id)).join(',')
    // 获取表缺失的行
    const payload = { tableName, id: getIds, dataList }
    dataList = await getTableList(payload)
    const newDatas = dataList.filter(e => idList.includes(e.id))
    return idList.length === 1 ? newDatas[0] : newDatas
  }
  // 获取部门列表，需要区分公司
  const getDeptList = async (id = null) => {
    const payload = { tableName: 'auth_department', id, dataList: deptList }
    deptList = await getTableList(payload)
    return deptList
  }
  // 根据 ids 获取部门列表
  const getDeptByIds = async (ids) => {
    const payload = { tableName: 'auth_department', id: ids, dataList: deptList }
    return await updateListById(payload)
  }
  // 获取角色列表
  const getRoleList = async (id = null) => {
    const payload = { tableName: 'auth_role', id, dataList: roleList }
    roleList = await getTableList(payload)
    return roleList
  }
  // 根据角色 ids 获取角色列表
  const getRoleByIds = async (ids) => {
    const payload = { tableName: 'auth_role', id: ids, dataList: roleList }
    return await updateListById(payload)
  }

  //  搜索用户
  const searchUserByMobile = debounce(async (e) => {
    const reqData = {
      mobile: `%${e}%`,
      deleted_at: 'NULL',
      limit: 10,
    }
    const { status, data } = await Fetch('/api/s/t/auth_user', { method: 'post', data: reqData })
    if (status !== 200 || data.code !== 0) {
      console.log(data.msg)
      return null
    }
    return data.result.dataList
  }, 500, { 'leading': true })

  return {
    deptList: $$(deptList),
    menuList: $$(menuList),
    roleList: $$(roleList),
    searchUserByMobile,
    roleListOptions,
    getDeptList,
    getDeptByIds,
    getRoleList,
    getRoleByIds,
    updateMenus,
  }
})

if (import.meta.hot)
  import.meta.hot.accept(acceptHMRUpdate(useCacheStore, import.meta.hot))
